package top.mczhengyi.xyblog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.mczhengyi.xyblog.auth.AuthManage;
import top.mczhengyi.xyblog.auth.RequireLogin;
import top.mczhengyi.xyblog.entity.Result;
import top.mczhengyi.xyblog.entity.ResultCode;
import top.mczhengyi.xyblog.entity.User;
import top.mczhengyi.xyblog.service.UserService;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @PostMapping("")
    public Result login(String uname, String pwd) {
        // GET USER OBJ
        User user = userService.getUserByUname(uname);
        if (user == null) {
            // NOT USER
            return Result.fail(ResultCode.NOT_USER);
        }
        if (!pwd.equals(user.getPassword())) {
            return Result.fail(ResultCode.WRONG_PWD);
        }
        String token = AuthManage.auth(user);
        return Result.success(token);
    }

    @GetMapping("")
    @RequireLogin
    public Result getUser(@RequestHeader(value = "TOKEN", required = false) String token) {
        User user = AuthManage.getUser(token);
        if (user == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        return Result.success(user);
    }
}
